package com.tzy.spi.aop.Interceptor;

import com.tzy.spi.aop.JoinPoint;
import com.tzy.spi.aop.annotition.CustomAnno;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class AfterMethodInterceptor extends AbstractMethodInterceptor{
    @Override
    public Object toDo(JoinPoint joinPoint) throws Throwable {

        try{
            return joinPoint.invoke();
        }finally {
            try {
                getMethod().invoke(getAspect(),buildParam(getMethod(),joinPoint));
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }

    }



    public Object[] buildParam(Method method,JoinPoint joinPoint){
        List<Object> objects =new ArrayList<>();


        if (method.getParameterCount()==0) {
            return objects.toArray();
        }

        for (Parameter parameter : method.getParameters()) {

            if(parameter.getAnnotation(CustomAnno.class)!=null){
                objects.add(joinPoint.annotation());
            }else {
                objects.add(null);
            }
        }

        return objects.toArray();

    }

}
